package groupTalk;

import java.io.*;
import java.net.Socket;

/**
 * 线程类，负责读取数据
 */
public class ServerReader extends Thread{
    private Socket socket;
    public ServerReader(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //3.获取输入流，读取数据
            InputStream is = socket.getInputStream();
            //4.把字节输入流封装特殊数据输入流
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try{
                    //5.读取数据
                    String msg = dis.readUTF();//等待读取客户端发送的数据
                    System.out.println("服务端收到msg：" + msg);
                    //6.客户端的ip和端口
                    System.out.println("客户端的ip:" + socket.getInetAddress().getHostAddress());
                    System.out.println("客户端的端口:" + socket.getPort());
                    //转发给所有在线客户端
                    sendMsgToAll(msg);
                    System.out.println("-------------------------------------");
                }catch (Exception e){
                    System.out.println("客户端下线了：" + socket.getInetAddress().getHostAddress());
                    //移出下线的客户端
                    ServerDemo2.sockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMsgToAll(String msg) throws Exception {
        //发送给全部在线的Socket管道接收
        for (Socket s : ServerDemo2.sockets) {
            OutputStream os = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}
